/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lucava.importer.java;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import lucava.metamodel.java.MetaModel;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

/**
 *
 * @author glenn
 */
public class XmlImporter {

    /**
     *
     * Load d'un fihier XML et transformation en MetaModel JAVA
     *
     * @param filename
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public MetaModel load(String filename) throws JDOMException, IOException {

        //Parsing du fichier XML via SAX
        SAXBuilder sxb = new SAXBuilder();
        Document document = sxb.build(new File(filename));
        return this.buildDocument(document);
    }

    /**
     * * Load d'un contenu XML et transformation en MetaModel JAVA
     *
     * @param content
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public MetaModel loadContent(String content) throws JDOMException, IOException {

        InputStream is = new ByteArrayInputStream(content.getBytes());
        //Parsing du fichier XML via SAX
        SAXBuilder sxb = new SAXBuilder();
        Document document = sxb.build(is);

        return this.buildDocument(document);

    }

    /**
     * Construction du metaModel
     *
     * @param document
     * @return
     */
    private MetaModel buildDocument(Document document) {
        MetaModel metaModel = new MetaModel();
        Element racine = document.getRootElement();

        //récupération des éléments "class"
        List<Element> classElements = racine.getChildren("class");

        //Pour chaque élément, on construit l'importer associé selon le stéréotype
        Iterator<Element> elmtIt = classElements.iterator();
        while (elmtIt.hasNext()) {
            Element current = elmtIt.next();
            IXmlElementImporter importer = this.buildImporter(current.getChildren("stereotype"));
            metaModel.add(importer.load(current));
        }

        return metaModel;
    }

    /**
     * Construction de l'importer associé selon les stéréotype d'un Element
     *
     * @param children
     * @return
     */
    private IXmlElementImporter buildImporter(List<Element> children) {
        Iterator<Element> elmtIt = children.iterator();
        while (elmtIt.hasNext()) {
            if (elmtIt.next().getAttributeValue("name").equals("interface")) {
                return new XmlInterfaceElementImporter();
            }
        }
        return new XmlClassElementImporter();

    }
}
